from collections import deque
import threading
import asyncio

class Tasker:
    def __init__(self):
        self.queue = deque()  # 双端队列：前端放高优先级任务，后端放扫描任务
        self.running = True
        self.lock = threading.Lock()  # 保证队列操作的线程安全
        self.thread = threading.Thread(target=self._run, daemon=True)
        self.loop = None
        self.thread.start()

    def _run(self):
        self.loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.loop)

        while self.running:
            try:
                # 线程安全地获取任务（从前端取，优先执行非扫描任务）
                with self.lock:
                    if not self.queue:  # 队列为空时短暂休眠，减少CPU占用
                        # loop.run_until_complete(asyncio.sleep(0.01))
                        continue
                    coro, is_scan_task = self.queue.popleft()  # 从前端取任务

                # 执行任务
                self.loop.run_until_complete(coro)

            except Exception as e:
                pass
                # print(f"任务执行异常: {e}")

        self.loop.close()

    def add_task(self, task, is_scan_task=False):
        """添加任务：非扫描任务插前端，扫描任务放后端"""
        with self.lock:
            if is_scan_task:
                # 扫描任务放队列后端（低优先级）
                self.queue.append((task, True))
            else:
                # 非扫描任务插队列前端（高优先级）
                self.queue.appendleft((task, False))

    def stop(self):
        self.running = False
        self.thread.join()

    def get_loop(self):
        return self.loop